<?php

class LikesController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

    public function deleteAction()
    {
    	$feed_id = $_POST['feed_id'];
    	$user_id = $this->session->get('user_id');

    	$data = array(
    				"feed_id"=>$feed_id,
    				"user_id"=>$user_id,
    				"type"=>"unlike"
    			);
    	
    	$result = array();
    	$likes = FeedsLikesTb::findFirst(array(
    			"conditions"=>"feed_id = ?0 and user_id = ?1",
    			"bind"=>array(0=>$feed_id,1=>$user_id)
    		));

    	if($likes == true){
	    	if($likes->delete()==false)
	    	{
	    		$messages='Are you insane?';
	    		
	    		$result['messages'] = $messages;
	    		$result['status'] = false;
	    	}
	    	else
	    	{
	    		$data['total_likes'] = FeedsLikesTb::countLikes($data['feed_id']);
	    		$result['status'] = true;
	    		$pusher = new Pusher(PUSHER_APP_KEY, PUSHER_APP_SECRET, PUSHER_APP_ID);
	            $pusher->trigger('my-channel', 'likes-update', $data);

   
	    	}
    	}

    	echo json_encode($result);
    	$this->view->disable();
    }

    public function insertAction()
    {
    	$feed_id = $_POST['feed_id'];
    	$user_id = $this->session->get('user_id');

    	$data = array(
    				"feed_id"=>$feed_id,
    				"user_id"=>$user_id,
    				"type"=>"like"
    			);
    	
    	if(FeedsLikesTb::findFirst(array(
    		"conditions"=>"feed_id = ?0 and user_id = ?1",
    		"bind"=>array(0=>$feed_id,1=>$user_id)
    		)) == true)
    	{
    		$data['total_likes'] = FeedsLikesTb::countLikes($data['feed_id']);
    		$result['status'] = true;
    		echo json_encode(($result));
    		$this->view->disable();
    		exit();
    	}


    	$result = array();
    	$likes = new FeedsLikesTb();
    	if($likes->save($data)==false)
    	{
    		$messages='';
    		foreach ($likes->getMessages() as $value)
    		{
    			$messages.=$value."<br>";
    		}
    		$result['messages'] = $messages;
    		$result['status'] = false;
    	}
    	else
    	{
    		$data['total_likes'] = FeedsLikesTb::countLikes($data['feed_id']);
 
    		$result['status'] = true;
    		$pusher = new Pusher(PUSHER_APP_KEY, PUSHER_APP_SECRET, PUSHER_APP_ID);
            $pusher->trigger('my-channel', 'likes-update', $data);
    	}


    	echo json_encode($result);
    	$this->view->disable();
    }

}

